package com.mk.zookeeper.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.CountDownLatch;

@Slf4j
@Configuration
public class ZooKeeperConfig {

    @Value("${zk.address}")
    String address;
    @Value("${zk.timeout}")
    int timeout;

    public ZooKeeperConfig() {
    }

    @Bean
    public ZooKeeper getZookeeper() {
        ZooKeeper zooKeeper = null;
        try {
            /**
             * CountDownLatch 用于标记线程是否执行完。
             */
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            zooKeeper = new ZooKeeper(address, timeout, (x) -> {
                if (Watcher.Event.KeeperState.SyncConnected == x.getState()) {
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            log.info("初始化zookeeper状态：{}", zooKeeper.getState());
        } catch (Exception e) {
            log.error(" 初始化Zookeeper连接状态异常: {}",e.getMessage());
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
